package com.good.akkaserver.model;

import java.lang.reflect.Method;

import com.good.akkaserver.event.ClientEvent;
import com.good.akkaserver.server.AkkaServer;
import com.good.akkaserver.server.ObjectPoolWorld;

import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

/**
 * 对应一个客户端连接 ，每一个客户端连接都会创建此 Fiber。 客户端所以的请求都会在此Fiber 中处理
 * 
 * @author GengQing 2014-4-4
 */
public class PlayerActor extends UntypedActor {

	LoggingAdapter log = Logging.getLogger(getContext().system(), this);
	
	private static final AkkaServer  akkaServer = AkkaServer.getInstance();

	private static ObjectPoolWorld objectPoolWorld = ObjectPoolWorld
			.getInstance();

	private static class CommandHandlerHolder {

		public CommandHandlerHolder(BaseEventHandle h, Method m) {
			this.handler = h;
			this.method = m;
		}

		public BaseEventHandle handler;
		public Method method;
	}

	/** 与客户端的链接 */
	private ChannelHandlerContext ctx;

	/** session ID,每一个客户端连接都会生成一个session ID */
	private int sessionID;
	
	/** 帐号ID */
	private String uid = "";
	


	public PlayerActor(int id) {
		this.setSessionID(id);
	}

	public PlayerActor(int id, ChannelHandlerContext ctx) {
		this.setSessionID(id);
		this.ctx = ctx;
	}
	

	@Override
	public void preStart() { // 启动时可以做一些东西

	}
	

	@Override
	public void postStop() {
		log.info("I am going to shutdown,uid:"+uid); 
	}

	@Override
	public void onReceive(Object arg0) throws Exception {
		if (arg0 instanceof ClientEvent) { 						// 来自客户端的事件
			handleClientEvent((ClientEvent) arg0);
		}
	}


	/** 处理客户端的请求, */
	private void handleClientEvent(ClientEvent event) {

		try { 
				byte[] obj = event.getConData();
				String receData=new String(obj);
				if (receData == null) return;
				sendToClient(receData);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			objectPoolWorld.returnClientEvent(event); // 把对象还给线程池
		}
	}
	
	

	/** 将消息发给客户端 */
	public void sendToClient(String message) {

		if (message == null) return;
		
		try {
			byte[] msgbyte =message.getBytes(); 
			ByteBuf resp = Unpooled.copiedBuffer(msgbyte);
			ctx.writeAndFlush(resp);
		} catch (Exception ex) {
			log.error("下发给客户端失败：{}", ex);
		} 
	}
	

	public int getSessionID() {
		return sessionID;
	}

	public void setSessionID(int sessionID) {
		this.sessionID = sessionID;
	}

	

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}
	
	



}
